from django.views import View
from django.shortcuts import render, HttpResponse, redirect
from web.forms.account import RegisterModelFOrm, SendSmsForm, LoginSMSForm, LoginForm
from django.conf import settings
from web import models
from django.http import JsonResponse


# 短袖发送页面
class RegisterView(View):
    """注册页面"""

    def get(self, request):
        form = RegisterModelFOrm()
        return render(request, 'web/register.html', {'form': form})

    def post(self, request):
        form = RegisterModelFOrm(data=request.POST)
        if form.is_valid():
            # 验证通过,写入数据库form.cleaned_data获取所有数据
            instance = form.save()  # 调用form内部方法会帮助你写入数据,还可以取出数据表里面没有的字段 返回刚才写入的数据对象
            return JsonResponse({'status': True, 'data': '/login'})
        else:
            return JsonResponse({'status': False, 'error': form.errors})


# 注册页面
class Semd_smsView(View):
    """注册页面"""

    def get(self, request):
        form = SendSmsForm(request, data=request.GET)  # 传递get请求过来的数据进行校验
        # 校验手机号
        if form.is_valid():
            # 校验全部通过
            return JsonResponse({'status': True})

        # form.errors保存所有报错信息
        return JsonResponse({'status': False, 'error': form.errors})


# 短信登录页面
class LoginSmsView(View):
    """短信登录页面"""

    def get(self, request):
        form = LoginSMSForm()
        return render(request, 'web/login_sms.html', {'form': form})

    def post(self, request):
        form = LoginSMSForm(request.POST)
        if form.is_valid():
            user_object = form.cleaned_data['phone']
            # 用户信息存入session
            print(user_object)
            return JsonResponse({'status': True, 'data': "/index"})
        return JsonResponse({'status': False, 'error': form.errors})


# 用户名登录
class LoginView(View):
    def get(self, request):
        form = LoginForm(request)
        return render(request, 'web/login.html', {'form': form})

    def post(self, request):
        form = LoginForm(request, request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            # user_object = models.UserInfo.objects.filter(username=username, password=password).first()
            # 当需要构建复杂的sql时可以使用Q对象
            from django.db.models import Q
            user_object = models.UserInfo.objects.filter(Q(email=username) | Q(phone=username)).filter(
                password=password).first()
            if user_object:
                return redirect('/index')

            form.add_error('username', '用户名密码错误')
        else:
            return render(request, 'web/login.html', {'form': form, 'error': form.errors})


# 验证码图片路由
class ImageCodeView(View):
    def get(self, request):
        """生成图片验证码"""
        from utils.image_code import check_code
        from io import BytesIO
        image_object, code = check_code()

        # 需要把验证码写入session中
        request.session['image_code'] = code
        request.session.set_expiry(60)  # 设置过期时间60秒
        # 把图片写入内存中
        stream = BytesIO()
        image_object.save(stream, 'png')

        return HttpResponse(stream.getvalue())  # 读取内存中的图片并返回


